<template>
    <div class="app-container flex">
        <div class="w-1/5 pr-4">
            <el-card class="analyze-res-card " >
                <template #header>
                    <div class="bg-blue-500 text-white font-bold p-2">选课咨询结果</div>
                </template>
                <el-scrollbar class="h-[500px]">
                    <component :is="allowAnalyze ? textModel : disabledView" v-model:html="markedHtml" />
                </el-scrollbar>
            </el-card>
        </div>
        <div class="w-4/5 ">
            <el-card style="background-color: rgb(246, 247, 251);  max-width: 1080px" >
                <template #header>
                    <div class="card-header font-bold">
                        <span>AI咨询</span>
                    </div>
                </template>
                <el-scrollbar height="450px">
                    <div class="flex flex-col space-y-4 ">
                        <div class="bg-blue-400  mt-2 max-w-lg p-2 rounded-lg bg-white flex items-start  float-left">
                            <img src="@/assets/Ai_images/ai-icon.png" alt="AI Icon" class="w-8 h-8 mr-2 rounded-full">
                            <span>欢迎使用VIP会员专属高考分析AI，请输入您的高考成绩和意愿，我们将提供最好的建议！</span>
                        </div>
                        <div v-html="aiContext" class="flex flex-col space-y-4 "></div>
                    </div>
                </el-scrollbar>
                <template #footer>
                    <div class="flex items-center ">

                        <el-input type="textarea" placeholder="shift+enter可换行" v-model="message" class="flex-1"
                            @keydown="handleKeyDown" />
                        <el-button class="w-12 ml-2 h-12 bg-[#409eff] text-white" @click="sendText"
                            :disabled="!allowAi || loading">
                            <span v-if="loading"><el-loading-spinner /></span> <!-- 进度条 -->
                            <span v-else>发送</span>
                        </el-button>
                    </div>

                </template>
            </el-card>
        </div>
    </div>
</template>

<script setup>
import { getAnalyze, isAlowAi, isAlowAnalyze, sendTextToAi } from '@/api/exam/analyze';
import { compile, computed, onBeforeMount, onMounted, ref } from 'vue';
import { marked } from 'marked';
import { v4 as uuidv4 } from 'uuid';
import textModel from '@/components/model/text-model.vue';
import disabledView from '@/components/disabled/disabled-view.vue';

const sessionId = uuidv4().substring(0, 8);
const analyze = ref("123");
const message = ref('');
const aiContext = ref("");
const allowAnalyze = ref(false);
const allowAi = ref(false);
const loading = ref(false); // 新增 loading 状态
let interval;

const markedHtml = computed(() => {
    return marked(analyze.value);
})

async function doAnalyze() {
    await getAnalyze().then(res => {
        if (res.code == 200) {
            analyze.value = JSON.parse(res.data.analyzeInfo).output.choices[0].message.content;
            console.log(analyze.value);
        }
    });
}

function sendText() {
    if (message.value.trim()) {
        aiContext.value += generateMyTalk(message.value);
        loading.value = true; // 设置为加载中
        sendTextToAi({ sessionId: sessionId, message: message.value }).then(() => {
            console.log(loading.value);
            loading.value = false; // 收到回复后重置加载状态
        });
        message.value = '';
    }
}

function initSocket() {
    console.log(sessionId);
    const ws = new WebSocket("ws://121.41.171.121/websocket/exam/ai/" + sessionId);
    ws.onmessage = (data) => {
        console.log(data);
        aiContext.value = aiContext.value + generateAiTalk(marked(data.data));
    };
    interval = setInterval(() => {
        console.log("定时器正常工作");
        ws.send("");
    }, 3000);
    ws.onclose = () => {
        clearInterval(interval);
    };
}

function generateMyTalk(data) {
    return `<div class="my-talk">${data}</div>`;
}

function generateAiTalk(data) {
    return `
        <div class="ai-talk">
            <img src="src/assets/Ai_images/ai-icon.png" alt="AI Icon" class="ai-compile w-8 h-8 mr-2 rounded-full">
            <span>${data}</span>
        </div>
    `;
}

async function analyzePermission() {
    await isAlowAnalyze().then(res => {
        allowAnalyze.value = res.data;
    });
}

async function aiPermission() {
    await isAlowAi().then(res => {
        allowAi.value = res.data;
    });
}

// 键盘事件处理函数
function handleKeyDown(event) {
    if (event.key === 'Enter') {
        if (!event.shiftKey) {
            event.preventDefault(); // 阻止换行
            sendText(); // 发送消息
        }
    }
}

onMounted(async () => {
    await doAnalyze();
    initSocket();
    await analyzePermission();
    await aiPermission();
});

onBeforeMount(() => {
    clearInterval(interval);
});
</script>

<style scoped>
.my-talk {
    @apply bg-blue-400;
}

.ai-talk {
    @apply flex items-start bg-white rounded-lg p-2 max-w-[70%];
    /* Tailwind class replacement */
}

.ai-talk::before {
    content: '';
    @apply inline-block w-8 h-8 mr-2 bg-cover;
    /* Tailwind class replacement */
    background-image: url('/path/to/ai-icon.png');
    /* 替换成实际的AI图标路径 */
}
</style>
